<?php

namespace frontend\modules\orders\controllers;

use frontend\modules\marketing\models\Coupon;
use backend\modules\shipping\models\Shipping;
use frontend\modules\base\controllers\BaseController;
use frontend\modules\orders\models\Invoice;
use frontend\modules\orders\models\OrderGoods;
use frontend\modules\cart\models\Cart;
use Yii;
use frontend\modules\orders\models\OrderInfo;
use frontend\modules\orders\models\search\OrderInfoSearch;
use yii\base\Exception;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * 订单生成，订单查询，订单状态修改。
 *
 * Class OrderinfoController
 * @package frontend\modules\orders\controllers
 */
class OrderinfoController extends BaseController
{
    public $enableCsrfValidation = false;

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * 获取订单列表信息
     * @desc 获取订单信息，token验证
     * @param string data[status] |状态|yes|1\2\3\4\5
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     *
     * @return bool|string
     */
    public function actionIndex()
    {
        $userinfo = $this->checkAccessToken();
        if(is_object($userinfo)) {
            if ($userinfo) {
                $post  = $this->post;
                $postData = $post['data'];
                $status = isset($postData['status'])?$postData['status']:1;
                if($status=='all') {
                    $orderARR = OrderInfo::find()->where(['user_id' => $userinfo->id,'cancel_status'=>0])->orderBy(['add_time'=>SORT_DESC])->asArray()->all();
                    foreach($orderARR as $k=>$v) {
                        if($v['pay_status']==0&&$v['shipping_status']==0&&$v['order_status']==0&&$v['cancel_status']==0){
                            $orderARR[$k]['status'] = 2;
                        }
                        if($v['pay_status']==2&&$v['shipping_status']==0&&$v['order_status']==1){
                            $orderARR[$k]['status'] = 3;
                        }
                        if($v['pay_status']==2&&$v['shipping_status']==1&&$v['order_status']==2){
                            $orderARR[$k]['status'] = 4;
                        }
                        if($v['pay_status']==2&&$v['shipping_status']==2&&$v['comment_status']==0){
                            $orderARR[$k]['status'] = 5;
                        }
                    }
                } elseif($status=='unpayed') {
                    $orderARR = OrderInfo::find()->where(['is_delete'=>0,'user_id' => $userinfo->id,'pay_status'=>0,'shipping_status'=>0,'order_status'=>0,'cancel_status'=>0])->orderBy(['add_time'=>SORT_DESC])->asArray()->all();
                } elseif($status=='unshipped'){
                    $orderARR = OrderInfo::find()->where(['is_delete'=>0,'user_id' => $userinfo->id,'pay_status'=>2,'shipping_status'=>0,'order_status'=>1])->orderBy(['add_time'=>SORT_DESC])->asArray()->all();
                } elseif($status=='unchecked'){
                    $orderARR = OrderInfo::find()->where(['is_delete'=>0,'user_id' => $userinfo->id,'pay_status'=>2,'shipping_status'=>1,'order_status'=>2])->orderBy(['add_time'=>SORT_DESC])->asArray()->all();
                } elseif($status=='uncomment'){
                    $orderARR = OrderInfo::find()->where(['is_delete'=>0,'user_id' => $userinfo->id,'pay_status'=>2,'shipping_status'=>2,'comment_status'=>0])->orderBy(['add_time'=>SORT_DESC])->asArray()->all();
                }
                if($orderARR) {
                    foreach ($orderARR as $k => $v) {
                        $orderARR[$k]['children'] = OrderGoods::find()
                            ->select('g.attrText,og.*,u.wx_name as refere_name,u.wx_images as refere_images')
                            ->from('order_goods AS og')
                            ->leftJoin('user AS u','u.qcode = og.refere_id')
                            ->leftJoin('goods AS g','g.goods_id = og.goods_id')
                            ->where(['order_id' => $v['order_id']])->asArray()->all();
                        $orderARR[$k]['Invoice'] = Invoice::find()->where(['order_id'=>$v['order_id']])->asArray()->one();

                    }
                }
                $message = ['code' => 200, 'message' => '获取订单成功', 'data' => $orderARR];
                return json_encode($message);
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 直接生成订单
     * @desc 不加入购物车直接提交订单
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string data[goodsid] |商品ID|yes|40位|
     * @param string data[refere_id] |推荐人ID|yes|40位|
     * @param string data[tel] |用户电话号码|yes|
     * @param string data[email] |收货人邮件|yes|
     * @param string data[consignee] |收货人名称|yes|
     * @param string data[country] |国家region_id|yes|
     * @param string data[province] |省份region_id|yes|
     * @param string data[city] |市区region_id|yes|
     * @param string data[district] |地区region_id|yes|
     * @param string data[address] |详细地址|yes|
     * @param string data[pay_id] |支付方式ID|yes|
     * @param string data[pay_name] |支付方式名称|yes|
     * @param string data[order_amount] |订单正常总价支付。shop_price总合|yes|
     * @param string data[goods_amount] |订单实际需支付总价。减去优惠|yes|
     * @param string data[coupon_money] |优惠券减掉价钱|yes|
     *
     * @param string data[isInvoice] |是否开发票|yes|0或1 0：不开，1：开
     * @param string data[invoice_type] |发票类型|yes|0或1或2 0：普通发票 1：电子发票 2：增值发票
     * @param string data[porc] |发票种类|yes|0或1 0：个人，1：公司
     * @param string data[c_name] |发票抬头公司全名|yes|
     * @param string data[c_code] |公司税号|yes|
     * @param string data[p_tel] |电话|yes|
     * @param string data[p_email] |邮箱|yes|
     *
     *
     * @param string data[coupon_user_id] |优惠券|yes|40位

     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     */
    public function actionDtoorder()
    {
        $userinfo = $this->checkAccessToken();

        if(is_object($userinfo)) {
            if ($userinfo) {
                $post = $this->post;
                $postData = $this->post['data'];

                $beginTransaction = Yii::$app->db->beginTransaction();
                try {
                    $order_id = OrderInfo::createOrder($postData);
                    $order_goods = new OrderGoods();
                    $order_goods->addByGoods($post, $order_id);
                    if($postData['isInvoice']){
                        Invoice::CreateInv($postData,$order_id);
                    }
                    if($postData['isCoupon']){
                        Coupon::userCoupon($order_id,$postData);
                    }
                    $order = OrderInfo::findOne($order_id);
                    $ordersn = $order->order_sn;
                    $tolfee = $order->goods_amount;
                    $message = ['code' => 200, 'message' => '下单成功', 'data' => ['ordersn'=>$ordersn,'tolfee'=>$tolfee,'openid' => $userinfo->openid, 'userid' => $userinfo->id, 'access_token' => $userinfo->access_token]];
                    $beginTransaction->commit();
                    return json_encode($message);
                }catch (Exception $e){
                    $beginTransaction->rollBack();
                    $message = ['code' => 500, 'message' => $e->getMessage()];
                    return json_encode($message);
                }
            }
        }else{
            return $userinfo;
        }
    }

    /**
     * 购物车生成订单
     * @desc 先生成表头createOrder（），再通过购物车生成货物订单addByCart（）
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string data[tel] |用户电话号码|yes|
     * @param string data[email] |收货人邮件|yes|
     * @param string data[consignee] |收货人名称|yes|
     * @param string data[country] |国家region_id|yes|
     * @param string data[province] |省份region_id|yes|
     * @param string data[city] |市区region_id|yes|
     * @param string data[district] |地区region_id|yes|
     * @param string data[address] |详细地址|yes|
     * @param string data[pay_id] |支付方式ID|yes|
     * @param string data[pay_name] |支付方式名称|yes|
     * @param string data[order_amount] |订单正常总价支付。shop_price总合|yes|
     * @param string data[goods_amount] |订单实际需支付总价。减去优惠|yes|
     * @param string data[coupon_money] |优惠券减掉价钱|yes|
     *
     *
     * @param string data[isInvoice] |是否开发票|yes|0或1 0：不开，1：开
     * @param string data[invoice_type] |发票类型|yes|0或1或2 0：普通发票 1：电子发票 2：增值发票
     * @param string data[porc] |发票种类|yes|0或1 0：个人，1：公司
     * @param string data[c_name] |发票抬头公司全名|yes|
     * @param string data[c_code] |公司税号|yes|
     * @param string data[p_tel] |电话|yes|
     * @param string data[p_email] |邮箱|yes|
     *
     * @param string data[coupon_user_id] |优惠券|yes|40位
     *
     * @return string data[].userid 用户ID
     * @return string data[].unionid 用户名字
     * @return string data[].access_token 用户令牌
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCtoorder()
    {
        $userinfo = $this->checkAccessToken();

        if(is_object($userinfo)) {
            if ($userinfo) {
                $postData = $this->post['data'];

                $beginTransaction = Yii::$app->db->beginTransaction();
                try {
                    $order_id = OrderInfo::createOrder($postData);
                    $cartARR = Cart::getCartWChecked();
                    if($cartARR==array()){
                        throw new Exception('购物车为空，不能提交此订单！');
                    }
                    $order_goods = new OrderGoods();
                    $order_goods->addByCart($cartARR, $order_id);
                    if($postData['isInvoice']){
                        Invoice::CreateInv($postData,$order_id);
                    }
                    if($postData['isCoupon']){
                        Coupon::userCoupon($order_id,$postData);
                    }

                    Cart::deleteAll(['user_id'=>Yii::$app->UserInfo->userid,'is_check'=>1]);
                    $beginTransaction->commit();

                    $order = OrderInfo::findOne($order_id);
                    $ordersn = $order->order_sn;
                    $tolfee = $order->goods_amount;
                    $message = ['code' => 200, 'message' => '下单成功', 'data' => ['ordersn'=>$ordersn,'tolfee'=>$tolfee,'openid' => $userinfo->openid, 'userid' => $userinfo->id, 'access_token' => $userinfo->access_token]];
                    return json_encode($message);
                } catch (Exception $e) {
                    $beginTransaction->rollBack();
                    $message = ['code' => 500, 'message' => $e->getMessage()];
                    return json_encode($message);
                }
            }
        } else{
            return $userinfo;
        }
    }

    /**
     * 获取活动货物
     * @desc 我的活动MyActive（）
     *
     * @param string $userid |用户ID|yes|40位|
     * @param string $access_token |令牌access_token|yes|32位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionMyactive()
    {
        $model = new OrderInfo();
        $goodsActive = $model->MyActive();
        $message = ['code' => 200, 'message' => '获取活动数据成功', 'data' => ['goodsActive'=>$goodsActive]];
        return json_encode($message);
    }

    /**
     * 确认收货
     * @desc pay_status 2、shipping_status 2、comment_status 0
     *
     * @param string $access_token |令牌access_token|yes|32位|
     * @param string $order_id |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return bool|string
     */
    public function actionCheckdelivery()
    {
        $userinfo = $this->checkAccessToken();

        if(is_object($userinfo)) {
            if ($userinfo) {
                $postData = $this->post['data'];
                $beginTransaction = Yii::$app->db->beginTransaction();
                try {
                    $order_id = $postData['order_id'];
                    $orderInfo = OrderInfo::findOne($order_id);
                    $orderInfo->pay_status = 2;
                    $orderInfo->shipping_status = 2;
                    $orderInfo->order_status = 3;
                    if(!$orderInfo->save()){
                        throw new Exception(json_encode($orderInfo->errors));
                    }
                    $message = ['code' => 200, 'message' => '确认收货成功！', 'data' => []];
                    $beginTransaction->commit();;
                    return json_encode($message);
                } catch (Exception $e) {
                    $beginTransaction->rollBack();
                    $message = ['code' => 500, 'message' => $e->getMessage()];
                    return json_encode($message);
                }
            }
        } else{
            return $userinfo;
        }
    }

    /**
     * 获取商品信息
     * @desc 获取商品信息
     *
     * @param string $data[order_id] |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionGetorderinfo()
    {
        $post = Yii::$app->request->post();
        $postData  = $post['data'];
        $order_id = $postData['order_id'];

        $orderARR = OrderGoods::find()
            ->select('g.*,oi.*')
            ->from('order_goods AS og')
            ->leftJoin('order_info AS oi','oi.order_id = og.order_id')
            ->leftJoin('goods AS g','g.goods_id = og.goods_id')
            ->where(['oi.order_id'=>$order_id])
            ->asArray()
            ->All();
        $message = ['code' => 200, 'message' => '确认收货成功！', 'data' => $orderARR];
        return json_encode($message);
    }

    /**
     * 提醒发货
     * @desc 提醒发货
     *
     * @param string $data[order_id] |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionWarm()
    {
        $post = Yii::$app->request->post();
        $postData  = $post['data'];
        $order_id = $postData['order_id'];
        $order = OrderInfo::findOne($order_id);
        $order->is_warm = 1;
        if($order->save()){
            $message = ['code' => 200, 'message' => '提醒发货成功 ！', 'data' => []];
            return json_encode($message);
        }
    }

    /**
     * 删除订单
     * @desc 删除订单
     *
     * @param string $data[order_id] |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionOrderdel()
    {
        $userinfo = $this->checkAccessToken();

        if(is_object($userinfo)) {
            if ($userinfo) {
                $order_id = $this->post['data']['order_id'];
                $order = OrderInfo::findOne($order_id);
                $order->is_delete  = 1;
                $order->order_status = 6;
                if($order->save()){
                    $message = ['code' => 200, 'message' => '删除成功 ！', 'data' => []];
                    return json_encode($message);
                }
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 取消订单
     * @desc 取消订单
     *
     * @param string $data[order_id] |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionOrdercancel()
    {
        $userinfo = $this->checkAccessToken();

        if(is_object($userinfo)) {
            if ($userinfo) {
                $order_id = $this->post['data']['order_id'];
                $order = OrderInfo::findOne($order_id);

                if($order->pay_status==0){
                    $order->pay_status = 0;
                    $order->shipping_status = 0;
                    $order->order_status = 5;
                    $order->cancel_status = 1;
                    if($order->save()){
                        $message = ['code' => 200, 'message' => '取消成功 ！', 'data' => []];
                        return json_encode($message);
                    }
                }
                $message = ['code' => 500, 'message' => '订单已付款不能取消 ！', 'data' => []];
                return json_encode($message);
            }
        } else {
            return $userinfo;
        }
    }

    /**
     * 物流轨迹
     * @desc 物流轨迹
     *
     * @param string $data[order_id] |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionShowwuliu()
    {
        $post = Yii::$app->request->post();
        $postData = $post['data'];
        $orderInfo = OrderInfo::findOne($postData['order_id']);

        if($orderInfo&&$orderInfo->shipping_status>=1) {
            $invoice_no = $orderInfo->invoice_no;
            $shipping = Shipping::findOne($orderInfo->shipping_id);
            if(!$shipping) {
                $message = ['code' => 200, 'message' => '订单详情获取不到物流轨迹，未发货 ！', 'data' => []];
                return json_encode($message);
            }
            $shipping_code = $shipping->shipping_code;
            $wuliuApi = new \backend\modules\orders\lib\WuliuApi();
            $arrJson = $wuliuApi->getOrderTracesByJson($shipping_code,$invoice_no);
            $arrARR = json_decode($arrJson,true);
            $arrARR['shipping_name'] = $shipping->shipping_name;
            $message = ['code' => 200, 'message' => '获取物流轨迹成功', 'data' => $arrARR];
            return json_encode($message);
        } else {
            $message = ['code' => 500, 'message' => '该订单无物流轨迹！', 'data' => []];
            return json_encode($message);
        }
    }

    /**
     * 货物订单收货详情
     * @desc 货物订单收货详情
     *
     * @param string $data[order_id] |订单ID|yes|40位|
     *
     * @return string message 提示信息
     * @return string code 错误编码
     * @exception 200 成功获取
     * @exception 400 token验证失败
     * @exception 500 服务器内部错误
     * @return string
     */
    public function actionOrderdetail()
    {
        $userid = Yii::$app->UserInfo->userid;
        if($userid) {
            $post = Yii::$app->request->post();
            $postData = $post['data'];
            $orderDetail = OrderInfo::find()
                ->select('oi.consignee,oi.tel,oi.address,oi.order_sn,oi.shipping_name,s.shipping_code,
                erprovince.region_name as provice_name,
                ercity.region_name as city_name,
                erdistrict.region_name as district_name')
                ->from('order_info AS oi')
                ->leftJoin('ecs_region AS erprovince','erprovince.region_id = oi.province')
                ->leftJoin('ecs_region AS ercity','ercity.region_id = oi.city')
                ->leftJoin('ecs_region AS erdistrict','erdistrict.region_id = oi.district')
                ->leftJoin('shipping AS s','s.shipping_id = oi.shipping_id')
                ->where(['oi.order_id'=>$postData['order_id']])
                ->asArray()
                ->All();

            $orderInfo = OrderInfo::findOne($postData['order_id']);
            $lastTraces = [];
            if($orderInfo&&$orderInfo->shipping_status>=1) {
                $invoice_no = $orderInfo->invoice_no;
                $shipping = Shipping::findOne($orderInfo->shipping_id);
                if(!$shipping) {
                    $message = ['code' => 200, 'message' => '订单详情获取不到物流轨迹，未发货 ！', 'data' => ['lastTraces'=>[],'orderDetail'=>$orderDetail]];
                    return json_encode($message);
                }
                $shipping_code = $shipping->shipping_code;
                $wuliuApi = new \backend\modules\orders\lib\WuliuApi();
                $arrJson = $wuliuApi->getOrderTracesByJson($shipping_code,$invoice_no);
                $arrJson = json_decode($arrJson,true);
                if($arrJson['Traces']){
                    $lastTraces = array_pop($arrJson['Traces']);
                }
            }

            $message = ['code' => 200, 'message' => '订单详情获取物流轨迹成功！', 'data' => ['lastTraces'=>$lastTraces,'orderDetail'=>$orderDetail]];
            return json_encode($message);
        }
    }
}
